package com.css.zfzx.fxpg.modules.workarea.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.modules.workarea.repository.FxWorkareaNativeRepository;
import com.css.zfzx.fxpg.modules.workarea.repository.FxWorkareaRepository;
import com.css.zfzx.fxpg.modules.workarea.repository.entity.FxWorkareaEntity;
import com.css.zfzx.fxpg.modules.workarea.service.FxWorkareaService;
import com.css.zfzx.fxpg.modules.workarea.viewobjects.FxWorkareaQueryParams;
import com.css.zfzx.fxpg.modules.workarea.viewobjects.FxWorkareaVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author leon
 * @date 2020-11-24
 */
@Service
@Slf4j
public class FxWorkareaServiceImpl implements FxWorkareaService {

    @Autowired
    private FxWorkareaRepository fxWorkareaRepository;
    @Autowired
    private FxWorkareaNativeRepository fxWorkareaNativeRepository;

    @Override
    public JSONObject queryFxWorkareas(FxWorkareaQueryParams queryParams, int curPage, int pageSize) {
        Page<FxWorkareaEntity> fxWorkareaPage = this.fxWorkareaNativeRepository.queryFxWorkareas(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxWorkareaPage);
        return jsonObject;
    }


    @Override
    public FxWorkareaEntity getFxWorkarea(String id) {
        FxWorkareaEntity fxWorkarea = this.fxWorkareaRepository.findById(id).orElse(null);
        return fxWorkarea;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxWorkareaEntity saveFxWorkarea(FxWorkareaEntity fxWorkarea) {
        String uuid = UUIDGenerator.getUUID();
        fxWorkarea.setId(uuid);
        fxWorkarea.setCreateUser(PlatformSessionUtils.getUserId());
        fxWorkarea.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxWorkareaRepository.save(fxWorkarea);
        return fxWorkarea;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxWorkareaEntity updateFxWorkarea(FxWorkareaEntity fxWorkarea) {
        fxWorkarea.setUpdateUser(PlatformSessionUtils.getUserId());
        fxWorkarea.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxWorkarea.getId();
        FxWorkareaEntity one = fxWorkareaRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxWorkarea, one);
        this.fxWorkareaRepository.save(one);
        return fxWorkarea;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxWorkareas(List<String> ids) {
        List<FxWorkareaEntity> fxWorkareaList = this.fxWorkareaRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(fxWorkareaList) && fxWorkareaList.size() > 0) {
            for (FxWorkareaEntity fxWorkarea : fxWorkareaList) {
                this.fxWorkareaRepository.delete(fxWorkarea);
            }
        }
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            params.setTitleRows(1);
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxWorkareaVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxWorkareaVO.class, params);
            List<FxWorkareaVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxWorkareaVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxWorkareaVO vo = iterator.next();
                    String error = "";
                    returnMsg.append("第" + vo.getRowNum() + "行" + vo.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if ("库中该数据最多一条，请管理员清理数据库冗余数据！".equals(e.getMessage())) {
                return e.getMessage();
            } else {
                return "导入失败，请检查数据正确性";
            }
        }
    }

    @Override
    public String exportExcel(FxWorkareaQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxWorkareaEntity> fxWorkareaEntities = fxWorkareaNativeRepository.listFxWorkareas(queryParams);
            // 深拷贝
            ArrayList<FxWorkareaVO> vos = new ArrayList<>();
            for (FxWorkareaEntity workareaEntity : fxWorkareaEntities) {
                FxWorkareaVO vo = new FxWorkareaVO();
                BeanUtils.copyProperties(workareaEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "预评估工作区信息统计", "预评估工作区信息", FxWorkareaVO.class, "预评估工作区.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private void saveExcel(List<FxWorkareaVO> list) {
        for (int i = 0; i < list.size(); i++) {
            FxWorkareaEntity workareaEntity = new FxWorkareaEntity();
            FxWorkareaVO vo = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(vo, workareaEntity);
            saveOrUpdate(workareaEntity);
        }
    }

    public void saveOrUpdate(FxWorkareaEntity workareaEntity) {
        FxWorkareaQueryParams queryParams = new FxWorkareaQueryParams();
        queryParams.setWorkspace(workareaEntity.getWorkspace());
        List<FxWorkareaEntity> workareaEntities = fxWorkareaNativeRepository.listFxWorkareas(queryParams);
        // 若查到数据为空，则新增
        if (CollectionUtils.isEmpty(workareaEntities)) {
            this.saveFxWorkarea(workareaEntity);
        } else {
            if (workareaEntities.size() == 1) {
                // 修改
                FxWorkareaEntity sourceWorkareaEntity = workareaEntities.get(0);
                BeanUtil.copyPropertiesIgnoreNull(workareaEntity, sourceWorkareaEntity);
                this.updateFxWorkarea(sourceWorkareaEntity);
            } else {
                throw new RuntimeException("库中该数据最多一条，请管理员清理数据库冗余数据！");
            }
        }
    }


    @Override
    public List<FxWorkareaEntity> fxWorkareaStatisticalAnalysis(FxWorkareaQueryParams queryParams) {
        List<FxWorkareaEntity> resultEntities = fxWorkareaNativeRepository.listFxWorkareasForStatistic(queryParams);
        return resultEntities;
    }

    @Override
    public List<String> getWorkspaces() {
        List<String> workspaces = fxWorkareaRepository.findWorkspaces();
        return workspaces;
    }

}
